Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [123]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('dogImages/train')
valid_files, valid_targets = load_dataset('dogImages/valid')
test_files, test_targets = load_dataset('dogImages/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.
In [124]:
dog_names
Out[124]:
['Affenpinscher',
 'Afghan_hound',
 'Airedale_terrier',
 'Akita',
 'Alaskan_malamute',
 'American_eskimo_dog',
 'American_foxhound',
 'American_staffordshire_terrier',
 'American_water_spaniel',
 'Anatolian_shepherd_dog',
 'Australian_cattle_dog',
 'Australian_shepherd',
 'Australian_terrier',
 'Basenji',
 'Basset_hound',
 'Beagle',
 'Bearded_collie',
 'Beauceron',
 'Bedlington_terrier',
 'Belgian_malinois',
 'Belgian_sheepdog',
 'Belgian_tervuren',
 'Bernese_mountain_dog',
 'Bichon_frise',
 'Black_and_tan_coonhound',
 'Black_russian_terrier',
 'Bloodhound',
 'Bluetick_coonhound',
 'Border_collie',
 'Border_terrier',
 'Borzoi',
 'Boston_terrier',
 'Bouvier_des_flandres',
 'Boxer',
 'Boykin_spaniel',
 'Briard',
 'Brittany',
 'Brussels_griffon',
 'Bull_terrier',
 'Bulldog',
 'Bullmastiff',
 'Cairn_terrier',
 'Canaan_dog',
 'Cane_corso',
 'Cardigan_welsh_corgi',
 'Cavalier_king_charles_spaniel',
 'Chesapeake_bay_retriever',
 'Chihuahua',
 'Chinese_crested',
 'Chinese_shar-pei',
 'Chow_chow',
 'Clumber_spaniel',
 'Cocker_spaniel',
 'Collie',
 'Curly-coated_retriever',
 'Dachshund',
 'Dalmatian',
 'Dandie_dinmont_terrier',
 'Doberman_pinscher',
 'Dogue_de_bordeaux',
 'English_cocker_spaniel',
 'English_setter',
 'English_springer_spaniel',
 'English_toy_spaniel',
 'Entlebucher_mountain_dog',
 'Field_spaniel',
 'Finnish_spitz',
 'Flat-coated_retriever',
 'French_bulldog',
 'German_pinscher',
 'German_shepherd_dog',
 'German_shorthaired_pointer',
 'German_wirehaired_pointer',
 'Giant_schnauzer',
 'Glen_of_imaal_terrier',
 'Golden_retriever',
 'Gordon_setter',
 'Great_dane',
 'Great_pyrenees',
 'Greater_swiss_mountain_dog',
 'Greyhound',
 'Havanese',
 'Ibizan_hound',
 'Icelandic_sheepdog',
 'Irish_red_and_white_setter',
 'Irish_setter',
 'Irish_terrier',
 'Irish_water_spaniel',
 'Irish_wolfhound',
 'Italian_greyhound',
 'Japanese_chin',
 'Keeshond',
 'Kerry_blue_terrier',
 'Komondor',
 'Kuvasz',
 'Labrador_retriever',
 'Lakeland_terrier',
 'Leonberger',
 'Lhasa_apso',
 'Lowchen',
 'Maltese',
 'Manchester_terrier',
 'Mastiff',
 'Miniature_schnauzer',
 'Neapolitan_mastiff',
 'Newfoundland',
 'Norfolk_terrier',
 'Norwegian_buhund',
 'Norwegian_elkhound',
 'Norwegian_lundehund',
 'Norwich_terrier',
 'Nova_scotia_duck_tolling_retriever',
 'Old_english_sheepdog',
 'Otterhound',
 'Papillon',
 'Parson_russell_terrier',
 'Pekingese',
 'Pembroke_welsh_corgi',
 'Petit_basset_griffon_vendeen',
 'Pharaoh_hound',
 'Plott',
 'Pointer',
 'Pomeranian',
 'Poodle',
 'Portuguese_water_dog',
 'Saint_bernard',
 'Silky_terrier',
 'Smooth_fox_terrier',
 'Tibetan_mastiff',
 'Welsh_springer_spaniel',
 'Wirehaired_pointing_griffon',
 'Xoloitzcuintli',
 'Yorkshire_terrier']

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [125]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [126]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[33])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray) # list of coordinates of boundary box around the face

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 2
In [127]:
faces
Out[127]:
array([[ 70,  68, 112, 112],
       [  0,   7,  76,  76]], dtype=int32)

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [128]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

In [129]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
'''
performance_human = []
performance_dog = []

for image in human_files_short:
    performance_human.append(face_detector(image))

for image in dog_files_short:
    performance_dog.append(face_detector(image))
    
# print number of faces detected in the image
print(' percentage of detected human face in human_files_short:', 100.0*sum(performance_human)/len(human_files_short))

print(' percentage of detected human face in dog_files_short:', 100.0*sum(performance_dog)/len(dog_files_short))
'''

performance_human = [image for image in human_files_short if face_detector(image)]
performance_dog = [image for image in dog_files_short if face_detector(image)]

print(' percentage of detected human face in human_files_short: {} %'.format(100.0*len(performance_human)/len(human_files_short)))
print(' percentage of detected human face in dog_files_short: {} %'.format(100.0*len(performance_dog)/len(dog_files_short)))
 percentage of detected human face in human_files_short: 98.0 %
 percentage of detected human face in dog_files_short: 11.0 %

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer:

It is reasonable to expect for a clear view of users' faces if the purpose of the algorithm is to only detect the human faces, not humans. However in the general sense, the restriction on a clear shot of faces to identify the humans in the pictures is unfair. Users can not control the angles of the faces. Therefore in order to identify human , the model must be trained with more features including different angles (i.e straight ears, back of heads, haircut, part of the body or full body image) beyond the clear view of human faces.


We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [130]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.

new_size = 224

    
def image_resize(image_path, crop_height=new_size, crop_width=new_size):
    image = cv2.imread(image_path)
    return cv2.resize(image,(crop_height, crop_width))

X_human = [image_resize(i) for i in human_files]
X_dog = [image_resize(i) for i in train_files]
In [131]:
# print statistics about the dataset
print('There are %d total resized human images.' % len(X_human))
print('There are %d total resized dog images.' % len(X_dog))

#print('There are {} total resized human images.'.format(len(X_human)))
#print('There are {} total resized dog images.'.format(len(X_dog)))
There are 13233 total resized human images.
There are 6680 total resized dog images.
In [140]:
X_human_short = X_human[:100]
X_dog_short = X_dog[:100]

y_human_short = [[1,0] for i in X_human_short]
y_dog_short = [[0,1] for i in X_dog_short]

X = np.concatenate((X_human_short, X_dog_short), axis=0)
y = np.concatenate((y_human_short, y_dog_short), axis=0)

print('There are %d total train images.' % len(X))
There are 200 total train images.
In [ ]:
 
In [165]:
print('Size of 3D tensor:', X[0].shape) # 3D tensor
print('Size of 4D tensor:', np.expand_dims(X[0], axis=0).shape) # 4D tensor
Size of 3D tensor: (224, 224, 3)
Size of 4D tensor: (1, 224, 224, 3)
In [167]:
X_human_test = X_human[200:300]
X_dog_test = X_dog[200:300]

y_human_test = [0 for i in X_human_test]
y_dog_test = [1 for i in X_dog_test]

X_test = np.concatenate((X_human_test, X_dog_test), axis=0)
y_test = np.concatenate((y_human_test, y_dog_test), axis=0)

print('There are %d total test images.' % len(X_test))
There are 200 total test images.
In [156]:
# Import keras deep learning libraries
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.callbacks import ModelCheckpoint

from keras.activations import relu
from keras.layers import ELU
from keras.optimizers import SGD, Adam
from keras.layers.advanced_activations import LeakyReLU


model = Sequential()
# Layer 1
model.add(Conv2D(filters = 16, 
                 kernel_size = (7, 7), 
                 strides=(1, 1), 
                 padding='same', 
                 input_shape=(new_size, new_size, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))


# Layer 2
model.add(Conv2D(filters = 32, 
                 kernel_size = (5, 5), 
                 padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same'))


# Layer 3
model.add(GlobalAveragePooling2D())
model.add(Dropout(0.2))


# Layer 4
model.add(Dense(256))
#model.add(Activation('relu'))
model.add(LeakyReLU(alpha=.001))
#model.add(Dropout(0.5))

# Layer 5
model.add(Dense(2))

# Output
#model.add(LeakyReLU(alpha=.001))
model.add(Activation('softmax'))


# Minimization
#adamopt = Adam(lr=0.0001)
#model.compile(optimizer=adamopt, loss='categorical_crossentropy', metrics=['accuracy'])
model.compile(optimizer='rmsprop', 
              loss='categorical_crossentropy', 
              metrics=['accuracy'])

# THE summary of the model
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_14 (Conv2D)           (None, 224, 224, 16)      2368      
_________________________________________________________________
activation_119 (Activation)  (None, 224, 224, 16)      0         
_________________________________________________________________
max_pooling2d_15 (MaxPooling (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_15 (Conv2D)           (None, 112, 112, 32)      12832     
_________________________________________________________________
activation_120 (Activation)  (None, 112, 112, 32)      0         
_________________________________________________________________
max_pooling2d_16 (MaxPooling (None, 112, 112, 32)      0         
_________________________________________________________________
global_average_pooling2d_6 ( (None, 32)                0         
_________________________________________________________________
dropout_6 (Dropout)          (None, 32)                0         
_________________________________________________________________
dense_11 (Dense)             (None, 256)               8448      
_________________________________________________________________
leaky_re_lu_3 (LeakyReLU)    (None, 256)               0         
_________________________________________________________________
dense_12 (Dense)             (None, 2)                 514       
_________________________________________________________________
activation_121 (Activation)  (None, 2)                 0         
=================================================================
Total params: 24,162.0
Trainable params: 24,162.0
Non-trainable params: 0.0
_________________________________________________________________
In [157]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights_human_vs_dog.h5', 
                               verbose=1, 
                               save_best_only=True)

model.fit(X, y, batch_size=32, epochs=100, verbose=1, callbacks=[checkpointer])
Epoch 1/100
200/200 [==============================] - 16s - loss: 7.4011 - acc: 0.5250     
/Users/ducvu/anaconda2/envs/aind-dog/lib/python3.5/site-packages/keras/callbacks.py:388: RuntimeWarning: Can save best model only with val_loss available, skipping.
  'skipping.' % (self.monitor), RuntimeWarning)
Epoch 2/100
200/200 [==============================] - 16s - loss: 8.0590 - acc: 0.5000      
Epoch 3/100
200/200 [==============================] - 17s - loss: 7.0777 - acc: 0.5000     
Epoch 4/100
200/200 [==============================] - 18s - loss: 0.7423 - acc: 0.4700     
Epoch 5/100
200/200 [==============================] - 18s - loss: 0.6947 - acc: 0.5250     
Epoch 6/100
200/200 [==============================] - 19s - loss: 0.6318 - acc: 0.6450     
Epoch 7/100
200/200 [==============================] - 17s - loss: 0.6244 - acc: 0.6300     
Epoch 8/100
200/200 [==============================] - 15s - loss: 0.5717 - acc: 0.7050     
Epoch 9/100
200/200 [==============================] - 17s - loss: 0.5412 - acc: 0.6750     
Epoch 10/100
200/200 [==============================] - 15s - loss: 1.4744 - acc: 0.6650     
Epoch 11/100
200/200 [==============================] - 15s - loss: 0.6328 - acc: 0.6700     
Epoch 12/100
200/200 [==============================] - 14s - loss: 0.8560 - acc: 0.7550     
Epoch 13/100
200/200 [==============================] - 15s - loss: 0.4281 - acc: 0.8050     
Epoch 14/100
200/200 [==============================] - 15s - loss: 0.8870 - acc: 0.6400     
Epoch 15/100
200/200 [==============================] - 14s - loss: 0.4441 - acc: 0.7800     
Epoch 16/100
200/200 [==============================] - 15s - loss: 0.4147 - acc: 0.8200     
Epoch 17/100
200/200 [==============================] - 14s - loss: 0.4094 - acc: 0.7850     
Epoch 18/100
200/200 [==============================] - 16s - loss: 0.3614 - acc: 0.8250     
Epoch 19/100
200/200 [==============================] - 15s - loss: 0.3921 - acc: 0.8200     
Epoch 20/100
200/200 [==============================] - 15s - loss: 0.3970 - acc: 0.7850     
Epoch 21/100
200/200 [==============================] - 13s - loss: 0.4668 - acc: 0.8550     
Epoch 22/100
200/200 [==============================] - 14s - loss: 1.5754 - acc: 0.7550     
Epoch 23/100
200/200 [==============================] - 14s - loss: 0.4030 - acc: 0.8550     
Epoch 24/100
200/200 [==============================] - 15s - loss: 0.5038 - acc: 0.7300     
Epoch 25/100
200/200 [==============================] - 15s - loss: 0.3337 - acc: 0.8500     
Epoch 26/100
200/200 [==============================] - 14s - loss: 0.3456 - acc: 0.8500     
Epoch 27/100
200/200 [==============================] - 14s - loss: 0.3401 - acc: 0.8350     
Epoch 28/100
200/200 [==============================] - 14s - loss: 1.7315 - acc: 0.7200     
Epoch 29/100
200/200 [==============================] - 14s - loss: 0.3594 - acc: 0.8650     
Epoch 30/100
200/200 [==============================] - 14s - loss: 0.2860 - acc: 0.8750     
Epoch 31/100
200/200 [==============================] - 15s - loss: 0.3516 - acc: 0.8250     
Epoch 32/100
200/200 [==============================] - 15s - loss: 0.2852 - acc: 0.9000     
Epoch 33/100
200/200 [==============================] - 14s - loss: 0.3856 - acc: 0.8200     
Epoch 34/100
200/200 [==============================] - 15s - loss: 0.5645 - acc: 0.8050     
Epoch 35/100
200/200 [==============================] - 14s - loss: 0.3153 - acc: 0.8800     
Epoch 36/100
200/200 [==============================] - 15s - loss: 0.2721 - acc: 0.9000     
Epoch 37/100
200/200 [==============================] - 15s - loss: 0.3426 - acc: 0.8350     
Epoch 38/100
200/200 [==============================] - 16s - loss: 0.3915 - acc: 0.8450     
Epoch 39/100
200/200 [==============================] - 16s - loss: 0.3265 - acc: 0.8300     
Epoch 40/100
200/200 [==============================] - 15s - loss: 0.2641 - acc: 0.9000     
Epoch 41/100
200/200 [==============================] - 15s - loss: 0.2214 - acc: 0.9100     
Epoch 42/100
200/200 [==============================] - 16s - loss: 3.4094 - acc: 0.7350     
Epoch 43/100
200/200 [==============================] - 16s - loss: 0.4918 - acc: 0.7500     
Epoch 44/100
200/200 [==============================] - 16s - loss: 0.8594 - acc: 0.7950     
Epoch 45/100
200/200 [==============================] - 15s - loss: 0.2674 - acc: 0.8950     
Epoch 46/100
200/200 [==============================] - 14s - loss: 0.2776 - acc: 0.8700     
Epoch 47/100
200/200 [==============================] - 14s - loss: 0.2985 - acc: 0.8600     
Epoch 48/100
200/200 [==============================] - 14s - loss: 0.2519 - acc: 0.9100     
Epoch 49/100
200/200 [==============================] - 15s - loss: 2.5843 - acc: 0.7450     
Epoch 50/100
200/200 [==============================] - 15s - loss: 0.4030 - acc: 0.7900     
Epoch 51/100
200/200 [==============================] - 14s - loss: 0.3015 - acc: 0.8550     
Epoch 52/100
200/200 [==============================] - 15s - loss: 0.1879 - acc: 0.9150     
Epoch 53/100
200/200 [==============================] - 15s - loss: 0.3076 - acc: 0.8700     
Epoch 54/100
200/200 [==============================] - 16s - loss: 0.2272 - acc: 0.8900     
Epoch 55/100
200/200 [==============================] - 15s - loss: 0.2103 - acc: 0.9150     
Epoch 56/100
200/200 [==============================] - 14s - loss: 0.3991 - acc: 0.8400     
Epoch 57/100
200/200 [==============================] - 15s - loss: 0.2307 - acc: 0.9100     
Epoch 58/100
200/200 [==============================] - 15s - loss: 0.5432 - acc: 0.7600     
Epoch 59/100
200/200 [==============================] - 15s - loss: 0.2095 - acc: 0.9300     
Epoch 60/100
200/200 [==============================] - 17s - loss: 0.2074 - acc: 0.9050     
Epoch 61/100
200/200 [==============================] - 16s - loss: 0.3268 - acc: 0.8300     
Epoch 62/100
200/200 [==============================] - 14s - loss: 0.3292 - acc: 0.8550     
Epoch 63/100
200/200 [==============================] - 13s - loss: 0.3452 - acc: 0.8550     
Epoch 64/100
200/200 [==============================] - 16s - loss: 0.2803 - acc: 0.8950     
Epoch 65/100
200/200 [==============================] - 16s - loss: 0.2571 - acc: 0.8850     
Epoch 66/100
200/200 [==============================] - 15s - loss: 0.3079 - acc: 0.8950     
Epoch 67/100
200/200 [==============================] - 15s - loss: 0.2394 - acc: 0.9000     
Epoch 68/100
200/200 [==============================] - 16s - loss: 0.1993 - acc: 0.9200     
Epoch 69/100
200/200 [==============================] - 14s - loss: 0.1893 - acc: 0.9150     
Epoch 70/100
200/200 [==============================] - 14s - loss: 0.2471 - acc: 0.8700     
Epoch 71/100
200/200 [==============================] - 15s - loss: 0.8088 - acc: 0.7850     
Epoch 72/100
200/200 [==============================] - 15s - loss: 0.1879 - acc: 0.9250     
Epoch 73/100
200/200 [==============================] - 14s - loss: 0.1855 - acc: 0.9450     
Epoch 74/100
200/200 [==============================] - 14s - loss: 0.2236 - acc: 0.8850     
Epoch 75/100
200/200 [==============================] - 14s - loss: 0.1853 - acc: 0.9300     
Epoch 76/100
200/200 [==============================] - 14s - loss: 0.3687 - acc: 0.8700     
Epoch 77/100
200/200 [==============================] - 14s - loss: 0.3780 - acc: 0.8450     
Epoch 78/100
200/200 [==============================] - 14s - loss: 0.1375 - acc: 0.9600     
Epoch 79/100
200/200 [==============================] - 14s - loss: 0.2831 - acc: 0.8850     
Epoch 80/100
200/200 [==============================] - 14s - loss: 0.1424 - acc: 0.9650     
Epoch 81/100
200/200 [==============================] - 14s - loss: 0.2457 - acc: 0.8850     
Epoch 82/100
200/200 [==============================] - 13s - loss: 0.2269 - acc: 0.8950     
Epoch 83/100
200/200 [==============================] - 14s - loss: 0.8985 - acc: 0.8150     
Epoch 84/100
200/200 [==============================] - 15s - loss: 0.4627 - acc: 0.7550     
Epoch 85/100
200/200 [==============================] - 14s - loss: 0.3185 - acc: 0.8250     
Epoch 86/100
200/200 [==============================] - 14s - loss: 0.3489 - acc: 0.8500     
Epoch 87/100
200/200 [==============================] - 13s - loss: 0.1577 - acc: 0.9250     
Epoch 88/100
200/200 [==============================] - 15s - loss: 0.1281 - acc: 0.9550     
Epoch 89/100
200/200 [==============================] - 14s - loss: 0.3201 - acc: 0.8600     
Epoch 90/100
200/200 [==============================] - 15s - loss: 0.1379 - acc: 0.9500     
Epoch 91/100
200/200 [==============================] - 16s - loss: 0.3787 - acc: 0.8750     
Epoch 92/100
200/200 [==============================] - 14s - loss: 0.1836 - acc: 0.9350     
Epoch 93/100
200/200 [==============================] - 13s - loss: 0.1795 - acc: 0.9250     
Epoch 94/100
200/200 [==============================] - 13s - loss: 0.2091 - acc: 0.9500     
Epoch 95/100
200/200 [==============================] - 13s - loss: 0.2163 - acc: 0.9250     
Epoch 96/100
200/200 [==============================] - 13s - loss: 0.1865 - acc: 0.9250     
Epoch 97/100
200/200 [==============================] - 14s - loss: 0.3072 - acc: 0.8450     
Epoch 98/100
200/200 [==============================] - 13s - loss: 0.1740 - acc: 0.9000     
Epoch 99/100
200/200 [==============================] - 13s - loss: 0.1407 - acc: 0.9500     
Epoch 100/100
200/200 [==============================] - 13s - loss: 0.7978 - acc: 0.8000     
Out[157]:
<keras.callbacks.History at 0x12d221d30>
In [169]:
# This will generate error since input of Convd layer is 4D tensor
[np.argmax(model.predict(i)) for i in X_test]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-169-c45f3f6053cc> in <module>()
----> 1 [np.argmax(model.predict(i)) for i in X_test]

<ipython-input-169-c45f3f6053cc> in <listcomp>(.0)
----> 1 [np.argmax(model.predict(i)) for i in X_test]

/Users/ducvu/anaconda2/envs/aind-dog/lib/python3.5/site-packages/keras/models.py in predict(self, x, batch_size, verbose)
    889         if self.model is None:
    890             self.build()
--> 891         return self.model.predict(x, batch_size=batch_size, verbose=verbose)
    892 
    893     def predict_on_batch(self, x):

/Users/ducvu/anaconda2/envs/aind-dog/lib/python3.5/site-packages/keras/engine/training.py in predict(self, x, batch_size, verbose)
   1552         x = _standardize_input_data(x, self._feed_input_names,
   1553                                     self._feed_input_shapes,
-> 1554                                     check_batch_axis=False)
   1555         if self.stateful:
   1556             if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:

/Users/ducvu/anaconda2/envs/aind-dog/lib/python3.5/site-packages/keras/engine/training.py in _standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
    119                                  ' to have ' + str(len(shapes[i])) +
    120                                  ' dimensions, but got array with shape ' +
--> 121                                  str(array.shape))
    122             for j, (dim, ref_dim) in enumerate(zip(array.shape, shapes[i])):
    123                 if not j and not check_batch_axis:

ValueError: Error when checking : expected conv2d_14_input to have 4 dimensions, but got array with shape (224, 224, 3)
In [170]:
# note : imputs of layers is 4D tensor (conv2d_14 (Conv2D) is (None, 224, 224, 16) )
y_prediction = [np.argmax(model.predict(np.expand_dims(i, axis=0))) for i in X_test]
In [171]:
correct_pred = np.sum(y_prediction == y_test)
print(' The accuracy: {} %'.format(100.0*correct_pred/len(y_test)))
 The accuracy: 92.5 %

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [172]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [173]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [174]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [175]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path) # return i-th category index ranging from 1 to 1000, 
    return ((prediction <= 268) & (prediction >= 151)) # dog between 151 to 268

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

In [176]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

performance_human = [img_path for img_path in human_files_short if dog_detector(img_path)]
performance_dog = [img_path for img_path in dog_files_short if dog_detector(img_path)]

print(' percentage of detected dog in human_files_short: {} %'.format(100.0*len(performance_human)/len(human_files_short)))
print(' percentage of detected dog in dog_files_short: {} %'.format(100.0*len(performance_dog)/len(dog_files_short)))
 percentage of detected dog in human_files_short: 1.0 %
 percentage of detected dog in dog_files_short: 100.0 %

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [122]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [02:17<00:00, 48.51it/s]
100%|██████████| 835/835 [00:15<00:00, 55.32it/s]
100%|██████████| 836/836 [00:15<00:00, 54.80it/s]

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

I adopted the suggested CNN architecture with some changes which works well with image classification task as well as preserving spatial relationship between between pixels by learning image features (An Intuitive Explanation of Convolutional Neural Networks). The designed CNN architecture comprises a sequence of Convolutional Layers as follows:

  • Added 3 Convolutional Layers configured with:

    • input_shape for the first Convolutional Layer is set to RGB image size 224x224 with depth of 3
    • number of filters (the dimensionality of the output space) are increased with each higher Convolutional Layer index in the Sequence (i.e. 16, 32, 64)
    • kernel_size ( 2D Convolutional Window size) is set to 2 (i.e. 2x2 window)
    • stride is set to 1
    • padding is set to 'same'
    • activation (Activation Function) is set to 'relu'
  • Added Max Pooling Layer after each Convolutional Layer configured with:

    • pool_size is set to 2
    • strides is set to 1
    • padding is set to 'same'
  • Applied the Global Average Pooling layer (GAP) to flatten the structure, which is much more effective than a simple Flatten() as GAP is more native to the convolution structure by enforcing correspondences between feature maps and categories. Thus the feature maps can be easily interpreted as categories confidence maps. Another advantage is that there is no parameter to optimize in the GAP thus overfitting is avoided at this layer. Futhermore, GAP sums out the spatial information, thus it is more robust to spatial translations of the input. We can see GAP as a structural regularizer that explicitly enforces feature maps to be confidence maps of concepts (categories) (What is global average pooling?) + Global Average Pooling Layers for Object Localization.
  • Applied Dropout layer with rate is set to 0.2 (i.e. the probability that the node gets dropped at a particular epoch to prevent overfitting or 20% chance that node will be turned off) to force additional generalization and offset the increased complexity caused by the 3 Convolutional Layers in the network.
  • Added fully connected Dense layer with 133 nodes
  • Applied the softmax activation for the output layer.
  • Compiled with Optimiser 'rmsprop' and Loss function 'categorical_crossentropy' for multi-class problem (i.e softmax activation, one-hot encoded target) which is contrast to 2-class problem with 'binary_crossentropy'( i.e sigmoid activation, scalar target)
  • Trained with:

    • Epochs is set to 10
    • Batch Size is set to 20
In [249]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
# Layer 1
model.add(Conv2D(filters = 16, 
                 kernel_size = (5, 5), 
                 strides=(1, 1), 
                 padding='same', 
                 input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))


# Layer 2
model.add(Conv2D(filters = 32, 
                 kernel_size = (5, 5), 
                 padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same'))


# Layer 3
model.add(Conv2D(filters = 64, 
                 kernel_size = (5, 5), 
                 padding='same'))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1), padding='same'))

# Layer 4
model.add(GlobalAveragePooling2D())
model.add(Dropout(0.2))

# Layer 5
model.add(Dense(133))

# Output
model.add(Activation('softmax'))

# summary of the model
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_301 (Conv2D)          (None, 224, 224, 16)      1216      
_________________________________________________________________
activation_176 (Activation)  (None, 224, 224, 16)      0         
_________________________________________________________________
max_pooling2d_20 (MaxPooling (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_302 (Conv2D)          (None, 112, 112, 32)      12832     
_________________________________________________________________
activation_177 (Activation)  (None, 112, 112, 32)      0         
_________________________________________________________________
max_pooling2d_21 (MaxPooling (None, 112, 112, 32)      0         
_________________________________________________________________
conv2d_303 (Conv2D)          (None, 112, 112, 64)      51264     
_________________________________________________________________
activation_178 (Activation)  (None, 112, 112, 64)      0         
_________________________________________________________________
max_pooling2d_22 (MaxPooling (None, 112, 112, 64)      0         
_________________________________________________________________
global_average_pooling2d_18  (None, 64)                0         
_________________________________________________________________
dropout_10 (Dropout)         (None, 64)                0         
_________________________________________________________________
dense_27 (Dense)             (None, 133)               8645      
_________________________________________________________________
activation_179 (Activation)  (None, 133)               0         
=================================================================
Total params: 73,957.0
Trainable params: 73,957.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [250]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [251]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 10

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/10
6660/6680 [============================>.] - ETA: 3s - loss: 4.8869 - acc: 0.0099       Epoch 00000: val_loss improved from inf to 4.87208, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 1081s - loss: 4.8869 - acc: 0.0099 - val_loss: 4.8721 - val_acc: 0.0084
Epoch 2/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.8625 - acc: 0.0138      Epoch 00001: val_loss did not improve
6680/6680 [==============================] - 1009s - loss: 4.8620 - acc: 0.0141 - val_loss: 4.9011 - val_acc: 0.0096
Epoch 3/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.8152 - acc: 0.0152       Epoch 00002: val_loss improved from 4.87208 to 4.82413, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 988s - loss: 4.8151 - acc: 0.0151 - val_loss: 4.8241 - val_acc: 0.0168
Epoch 4/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.7690 - acc: 0.0191       Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 988s - loss: 4.7684 - acc: 0.0190 - val_loss: 4.8954 - val_acc: 0.0240
Epoch 5/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.7327 - acc: 0.0246       Epoch 00004: val_loss improved from 4.82413 to 4.74347, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 1012s - loss: 4.7324 - acc: 0.0246 - val_loss: 4.7435 - val_acc: 0.0335
Epoch 6/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.6970 - acc: 0.0291      Epoch 00005: val_loss improved from 4.74347 to 4.70740, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 964s - loss: 4.6967 - acc: 0.0290 - val_loss: 4.7074 - val_acc: 0.0359
Epoch 7/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.6539 - acc: 0.0317      Epoch 00006: val_loss improved from 4.70740 to 4.65105, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 975s - loss: 4.6534 - acc: 0.0317 - val_loss: 4.6511 - val_acc: 0.0347
Epoch 8/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.6121 - acc: 0.0396  Epoch 00007: val_loss improved from 4.65105 to 4.59067, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 1015s - loss: 4.6130 - acc: 0.0395 - val_loss: 4.5907 - val_acc: 0.0455
Epoch 9/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.5515 - acc: 0.0437   Epoch 00008: val_loss improved from 4.59067 to 4.51800, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 940s - loss: 4.5505 - acc: 0.0437 - val_loss: 4.5180 - val_acc: 0.0443
Epoch 10/10
6660/6680 [============================>.] - ETA: 2s - loss: 4.4825 - acc: 0.0441  Epoch 00009: val_loss improved from 4.51800 to 4.47782, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 971s - loss: 4.4825 - acc: 0.0440 - val_loss: 4.4778 - val_acc: 0.0515
Out[251]:
<keras.callbacks.History at 0x70f5038d0>

Load the Model with the Best Validation Loss

In [252]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [253]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 6.5789%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [180]:
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
In [259]:
print('Size of dog dataset :',train_VGG16.shape[0] + valid_VGG16.shape[0] + test_VGG16.shape[0])
Size of dog dataset : 8351

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [181]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_8 ( (None, 512)               0         
_________________________________________________________________
dense_15 (Dense)             (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________

Compile the Model

In [182]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [183]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6660/6680 [============================>.] - ETA: 0s - loss: 12.4551 - acc: 0.1128      Epoch 00000: val_loss improved from inf to 10.65744, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s - loss: 12.4535 - acc: 0.1130 - val_loss: 10.6574 - val_acc: 0.2072
Epoch 2/20
6380/6680 [===========================>..] - ETA: 0s - loss: 9.8796 - acc: 0.2785 Epoch 00001: val_loss improved from 10.65744 to 9.66757, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.8750 - acc: 0.2792 - val_loss: 9.6676 - val_acc: 0.2958
Epoch 3/20
6540/6680 [============================>.] - ETA: 0s - loss: 9.3631 - acc: 0.3532 Epoch 00002: val_loss improved from 9.66757 to 9.42249, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.3436 - acc: 0.3549 - val_loss: 9.4225 - val_acc: 0.3365
Epoch 4/20
6460/6680 [============================>.] - ETA: 0s - loss: 9.1447 - acc: 0.3878Epoch 00003: val_loss improved from 9.42249 to 9.39695, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 9.1545 - acc: 0.3873 - val_loss: 9.3969 - val_acc: 0.3425
Epoch 5/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.0734 - acc: 0.4018Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 9.0599 - acc: 0.4028 - val_loss: 9.4060 - val_acc: 0.3437
Epoch 6/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.8817 - acc: 0.4207Epoch 00005: val_loss improved from 9.39695 to 9.33992, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.9172 - acc: 0.4186 - val_loss: 9.3399 - val_acc: 0.3473
Epoch 7/20
6420/6680 [===========================>..] - ETA: 0s - loss: 8.8314 - acc: 0.4319 Epoch 00006: val_loss improved from 9.33992 to 9.20373, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.8192 - acc: 0.4325 - val_loss: 9.2037 - val_acc: 0.3569
Epoch 8/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.6499 - acc: 0.4416Epoch 00007: val_loss improved from 9.20373 to 9.09428, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.6669 - acc: 0.4409 - val_loss: 9.0943 - val_acc: 0.3820
Epoch 9/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.5418 - acc: 0.4555Epoch 00008: val_loss improved from 9.09428 to 8.92653, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.5384 - acc: 0.4554 - val_loss: 8.9265 - val_acc: 0.3880
Epoch 10/20
6540/6680 [============================>.] - ETA: 0s - loss: 8.4187 - acc: 0.4656Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 8.4187 - acc: 0.4657 - val_loss: 9.0196 - val_acc: 0.3677
Epoch 11/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.3817 - acc: 0.4718 Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 8.3785 - acc: 0.4720 - val_loss: 8.9360 - val_acc: 0.3868
Epoch 12/20
6540/6680 [============================>.] - ETA: 0s - loss: 8.3653 - acc: 0.4752 Epoch 00011: val_loss improved from 8.92653 to 8.92125, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.3616 - acc: 0.4753 - val_loss: 8.9213 - val_acc: 0.3856
Epoch 13/20
6440/6680 [===========================>..] - ETA: 0s - loss: 8.3865 - acc: 0.4753Epoch 00012: val_loss improved from 8.92125 to 8.83275, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.3515 - acc: 0.4772 - val_loss: 8.8327 - val_acc: 0.3880
Epoch 14/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.2359 - acc: 0.4783 Epoch 00013: val_loss improved from 8.83275 to 8.73509, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.2338 - acc: 0.4786 - val_loss: 8.7351 - val_acc: 0.3916
Epoch 15/20
6460/6680 [============================>.] - ETA: 0s - loss: 8.0959 - acc: 0.4850 Epoch 00014: val_loss improved from 8.73509 to 8.72783, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 8.0888 - acc: 0.4853 - val_loss: 8.7278 - val_acc: 0.3904
Epoch 16/20
6420/6680 [===========================>..] - ETA: 0s - loss: 7.8198 - acc: 0.4977Epoch 00015: val_loss improved from 8.72783 to 8.27281, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.8051 - acc: 0.4979 - val_loss: 8.2728 - val_acc: 0.4251
Epoch 17/20
6540/6680 [============================>.] - ETA: 0s - loss: 7.4907 - acc: 0.5206Epoch 00016: val_loss improved from 8.27281 to 8.09495, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.5229 - acc: 0.5186 - val_loss: 8.0950 - val_acc: 0.4323
Epoch 18/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.4544 - acc: 0.5261Epoch 00017: val_loss improved from 8.09495 to 8.07100, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.4410 - acc: 0.5268 - val_loss: 8.0710 - val_acc: 0.4323
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 7.3325 - acc: 0.5312Epoch 00018: val_loss improved from 8.07100 to 8.05687, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.3371 - acc: 0.5310 - val_loss: 8.0569 - val_acc: 0.4347
Epoch 20/20
6600/6680 [============================>.] - ETA: 0s - loss: 7.1588 - acc: 0.5398Epoch 00019: val_loss improved from 8.05687 to 7.86663, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 1s - loss: 7.1528 - acc: 0.5404 - val_loss: 7.8666 - val_acc: 0.4431
Out[183]:
<keras.callbacks.History at 0x1685304a8>

Load the Model with the Best Validation Loss

In [184]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [185]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 43.0622%

Predict Dog Breed with the Model

In [186]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']

Resnet50

In [194]:
### TODO: Obtain bottleneck features from pre-trained CNN Resnet50

bottleneck_features = np.load('bottleneck_features/DogResnet50Data.npz')
train_Resnet50 = bottleneck_features['train']
valid_Resnet50 = bottleneck_features['valid']
test_Resnet50 = bottleneck_features['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

Model Accuracy on the test set (%)
VGG-16 43.0622
VGG-19 45.6938
ResNet-50 82.0574
Inception 78.588
Xception 85.0478

I used transfer learning to create a CNN using Xception bottleneck features because it has a higher success rate in the image dataset. The training image dataset (8351 images) is rather small and its type is similiar to larger image dataset (dog is a component of larger training image dataset which Xception architecture is trained on), which falls under "Case 1" of the Transfer Learning lecture.

The suggested steps for "Case 1: Small Data Sets, Similar Data" are:

  • Slice off the end of the neural network

  • Add a new fully connected layer that matches the classes of the new data set

  • Randomize the weights of the new fully connected layer; freeze all weights from the pre-trained network

  • Train the network to update the weights of the new fully connected layer

The final CNN is implemented as follow:

  • Loading the bottleneck features from the pre-trained Xception model in as input

  • Applying a 2D Global Average Pooling layer (GAP) as dimensionality reduction to flatten the 3D input into a Vector

  • Feeding the vector into a dense, Fully Connected layer with 133 output nodes

  • Applying softmax activation layer with the 133 units given to output predictions for all the possible 133 dog breeds.

This architecture works well in image recognition because Xception is pre-trained on ImageNet dataset that also contains animal images.

In [188]:
### TODO: Define your architecture.
Resnet50_model = Sequential()
Resnet50_model.add(GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]))
Resnet50_model.add(Dense(133, activation='softmax'))

Resnet50_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_9 ( (None, 2048)              0         
_________________________________________________________________
dense_16 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [189]:
### TODO: Compile the model.
Resnet50_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [190]:
### TODO: Train the model.
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Resnet50.hdf5', 
                               verbose=1, save_best_only=True)

Resnet50_model.fit(train_Resnet50, train_targets, 
          validation_data=(valid_Resnet50, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6620/6680 [============================>.] - ETA: 0s - loss: 1.6284 - acc: 0.5962      Epoch 00000: val_loss improved from inf to 0.75715, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 3s - loss: 1.6196 - acc: 0.5978 - val_loss: 0.7571 - val_acc: 0.7653
Epoch 2/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.4383 - acc: 0.8644Epoch 00001: val_loss improved from 0.75715 to 0.73052, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s - loss: 0.4372 - acc: 0.8642 - val_loss: 0.7305 - val_acc: 0.7796
Epoch 3/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.2639 - acc: 0.9184Epoch 00002: val_loss improved from 0.73052 to 0.68437, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 1s - loss: 0.2652 - acc: 0.9177 - val_loss: 0.6844 - val_acc: 0.7964
Epoch 4/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1807 - acc: 0.9422Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.1807 - acc: 0.9419 - val_loss: 0.6921 - val_acc: 0.7976
Epoch 5/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.1234 - acc: 0.9612Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.1241 - acc: 0.9612 - val_loss: 0.6863 - val_acc: 0.7988
Epoch 6/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0865 - acc: 0.9750Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0858 - acc: 0.9753 - val_loss: 0.7063 - val_acc: 0.7976
Epoch 7/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0687 - acc: 0.9807Epoch 00006: val_loss improved from 0.68437 to 0.66710, saving model to saved_models/weights.best.Resnet50.hdf5
6680/6680 [==============================] - 2s - loss: 0.0692 - acc: 0.9805 - val_loss: 0.6671 - val_acc: 0.8204
Epoch 8/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0487 - acc: 0.9874Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0497 - acc: 0.9870 - val_loss: 0.7136 - val_acc: 0.8263
Epoch 9/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0375 - acc: 0.9902Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0377 - acc: 0.9901 - val_loss: 0.7766 - val_acc: 0.8132
Epoch 10/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.0304 - acc: 0.9916Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0302 - acc: 0.9918 - val_loss: 0.7476 - val_acc: 0.8192
Epoch 11/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0226 - acc: 0.9947Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0225 - acc: 0.9948 - val_loss: 0.7725 - val_acc: 0.8323
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0181 - acc: 0.9950Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0181 - acc: 0.9951 - val_loss: 0.8243 - val_acc: 0.8335
Epoch 13/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.0147 - acc: 0.9968Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0146 - acc: 0.9969 - val_loss: 0.7984 - val_acc: 0.8240
Epoch 14/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0126 - acc: 0.9970Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0126 - acc: 0.9970 - val_loss: 0.9174 - val_acc: 0.8228
Epoch 15/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.0105 - acc: 0.9976    Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0110 - acc: 0.9975 - val_loss: 0.8410 - val_acc: 0.8108
Epoch 16/20
6460/6680 [============================>.] - ETA: 0s - loss: 0.0090 - acc: 0.9975    Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0094 - acc: 0.9975 - val_loss: 0.8729 - val_acc: 0.8287
Epoch 17/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0063 - acc: 0.9977    Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0063 - acc: 0.9978 - val_loss: 0.8898 - val_acc: 0.8216
Epoch 18/20
6420/6680 [===========================>..] - ETA: 0s - loss: 0.0071 - acc: 0.9981    Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0069 - acc: 0.9982 - val_loss: 0.9296 - val_acc: 0.8132
Epoch 19/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.0065 - acc: 0.9978    Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0067 - acc: 0.9978 - val_loss: 0.8543 - val_acc: 0.8311
Epoch 20/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0062 - acc: 0.9988    Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 0.0060 - acc: 0.9988 - val_loss: 0.8847 - val_acc: 0.8180
Out[190]:
<keras.callbacks.History at 0x12d171320>

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [192]:
### TODO: Load the model weights with the best validation loss.
Resnet50_model.load_weights('saved_models/weights.best.Resnet50.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [193]:
### TODO: Calculate classification accuracy on the test dataset.
# get index of predicted dog breed for each image in test set
Resnet50_predictions = [np.argmax(Resnet50_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Resnet50]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Resnet50_predictions)==np.argmax(test_targets, axis=1))/len(Resnet50_predictions)
print('Test accuracy for Resnet50 : %.4f%%' % test_accuracy)
Test accuracy for Resnet50 : 82.0574%

VG19

In [195]:
### TODO: Obtain bottleneck features from pre-trained CNN VG19

bottleneck_features = np.load('bottleneck_features/DogVGG19Data.npz')
train_VGG19 = bottleneck_features['train']
valid_VGG19 = bottleneck_features['valid']
test_VGG19 = bottleneck_features['test']
In [196]:
VGG19_model = Sequential()
VGG19_model.add(GlobalAveragePooling2D(input_shape=train_VGG19.shape[1:]))
VGG19_model.add(Dense(133, activation='softmax'))

VGG19_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_10  (None, 512)               0         
_________________________________________________________________
dense_17 (Dense)             (None, 133)               68229     
=================================================================
Total params: 68,229.0
Trainable params: 68,229.0
Non-trainable params: 0.0
_________________________________________________________________
In [197]:
VGG19_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
In [198]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG19.hdf5', 
                               verbose=1, save_best_only=True)

VGG19_model.fit(train_VGG19, train_targets, 
          validation_data=(valid_VGG19, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6440/6680 [===========================>..] - ETA: 0s - loss: 12.0424 - acc: 0.1227  Epoch 00000: val_loss improved from inf to 10.11442, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s - loss: 12.0003 - acc: 0.1247 - val_loss: 10.1144 - val_acc: 0.2204
Epoch 2/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.2679 - acc: 0.3024 Epoch 00001: val_loss improved from 10.11442 to 8.95242, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 9.2519 - acc: 0.3034 - val_loss: 8.9524 - val_acc: 0.3293
Epoch 3/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.3708 - acc: 0.3918Epoch 00002: val_loss improved from 8.95242 to 8.52266, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 2s - loss: 8.3659 - acc: 0.3918 - val_loss: 8.5227 - val_acc: 0.3701
Epoch 4/20
6440/6680 [===========================>..] - ETA: 0s - loss: 7.9511 - acc: 0.4466Epoch 00003: val_loss improved from 8.52266 to 8.42220, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.9544 - acc: 0.4466 - val_loss: 8.4222 - val_acc: 0.3868
Epoch 5/20
6540/6680 [============================>.] - ETA: 0s - loss: 7.8432 - acc: 0.4659Epoch 00004: val_loss improved from 8.42220 to 8.22026, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.7935 - acc: 0.4686 - val_loss: 8.2203 - val_acc: 0.3976
Epoch 6/20
6560/6680 [============================>.] - ETA: 0s - loss: 7.4789 - acc: 0.4916Epoch 00005: val_loss improved from 8.22026 to 8.05196, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.5007 - acc: 0.4903 - val_loss: 8.0520 - val_acc: 0.4156
Epoch 7/20
6520/6680 [============================>.] - ETA: 0s - loss: 7.3644 - acc: 0.5140Epoch 00006: val_loss improved from 8.05196 to 8.04310, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.3490 - acc: 0.5147 - val_loss: 8.0431 - val_acc: 0.4240
Epoch 8/20
6480/6680 [============================>.] - ETA: 0s - loss: 7.2649 - acc: 0.5238Epoch 00007: val_loss improved from 8.04310 to 7.89664, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.2544 - acc: 0.5240 - val_loss: 7.8966 - val_acc: 0.4311
Epoch 9/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.1614 - acc: 0.5363Epoch 00008: val_loss improved from 7.89664 to 7.87199, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.1694 - acc: 0.5359 - val_loss: 7.8720 - val_acc: 0.4407
Epoch 10/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.0477 - acc: 0.5455Epoch 00009: val_loss improved from 7.87199 to 7.69629, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 7.0454 - acc: 0.5457 - val_loss: 7.6963 - val_acc: 0.4467
Epoch 11/20
6440/6680 [===========================>..] - ETA: 0s - loss: 6.9240 - acc: 0.5557Epoch 00010: val_loss improved from 7.69629 to 7.65962, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.9182 - acc: 0.5561 - val_loss: 7.6596 - val_acc: 0.4539
Epoch 12/20
6640/6680 [============================>.] - ETA: 0s - loss: 6.8414 - acc: 0.5664Epoch 00011: val_loss improved from 7.65962 to 7.63208, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.8415 - acc: 0.5665 - val_loss: 7.6321 - val_acc: 0.4611
Epoch 13/20
6460/6680 [============================>.] - ETA: 0s - loss: 6.8183 - acc: 0.5690Epoch 00012: val_loss improved from 7.63208 to 7.62276, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.8290 - acc: 0.5684 - val_loss: 7.6228 - val_acc: 0.4479
Epoch 14/20
6560/6680 [============================>.] - ETA: 0s - loss: 6.8153 - acc: 0.5721Epoch 00013: val_loss improved from 7.62276 to 7.57702, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.8192 - acc: 0.5719 - val_loss: 7.5770 - val_acc: 0.4635
Epoch 15/20
6420/6680 [===========================>..] - ETA: 0s - loss: 6.8270 - acc: 0.5718Epoch 00014: val_loss improved from 7.57702 to 7.56949, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.8124 - acc: 0.5729 - val_loss: 7.5695 - val_acc: 0.4563
Epoch 16/20
6520/6680 [============================>.] - ETA: 0s - loss: 6.7969 - acc: 0.5730 Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 6.8007 - acc: 0.5728 - val_loss: 7.6149 - val_acc: 0.4611
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 6.7143 - acc: 0.5740Epoch 00016: val_loss improved from 7.56949 to 7.52177, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.7237 - acc: 0.5734 - val_loss: 7.5218 - val_acc: 0.4599
Epoch 18/20
6420/6680 [===========================>..] - ETA: 0s - loss: 6.6415 - acc: 0.5799Epoch 00017: val_loss improved from 7.52177 to 7.51153, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.6560 - acc: 0.5792 - val_loss: 7.5115 - val_acc: 0.4659
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 6.6257 - acc: 0.5843Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 1s - loss: 6.6219 - acc: 0.5846 - val_loss: 7.5449 - val_acc: 0.4635
Epoch 20/20
6580/6680 [============================>.] - ETA: 0s - loss: 6.5418 - acc: 0.5865Epoch 00019: val_loss improved from 7.51153 to 7.46197, saving model to saved_models/weights.best.VGG19.hdf5
6680/6680 [==============================] - 1s - loss: 6.5310 - acc: 0.5868 - val_loss: 7.4620 - val_acc: 0.4695
Out[198]:
<keras.callbacks.History at 0x19b24c518>
In [199]:
VGG19_model.load_weights('saved_models/weights.best.VGG19.hdf5')
In [200]:
# get index of predicted dog breed for each image in test set
VGG19_predictions = [np.argmax(VGG19_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG19]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG19_predictions)==np.argmax(test_targets, axis=1))/len(VGG19_predictions)
print('Test accuracy for VG19: %.4f%%' % test_accuracy)
Test accuracy for VG19: 45.6938%

InceptionV3

In [202]:
### TODO: Obtain bottleneck features from pre-trained CNN InceptionV3

bottleneck_features = np.load('bottleneck_features/DogInceptionV3Data.npz')
train_InceptionV3 = bottleneck_features['train']
valid_InceptionV3 = bottleneck_features['valid']
test_InceptionV3 = bottleneck_features['test']
In [211]:
InceptionV3_model = Sequential()
InceptionV3_model.add(GlobalAveragePooling2D(input_shape=train_InceptionV3.shape[1:]))
#InceptionV3_model.add(Dense(512))
#InceptionV3_model.add(Activation('tanh'))
#InceptionV3_model.add(Dropout(0.2))
InceptionV3_model.add(Dense(133, activation='softmax'))

InceptionV3_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_14  (None, 2048)              0         
_________________________________________________________________
dense_23 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________
In [212]:
InceptionV3_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
In [213]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.InceptionV3.hdf5', 
                               verbose=1, save_best_only=True)

InceptionV3_model.fit(train_InceptionV3, train_targets, 
          validation_data=(valid_InceptionV3, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6560/6680 [============================>.] - ETA: 0s - loss: 1.1523 - acc: 0.7113      Epoch 00000: val_loss improved from inf to 0.61711, saving model to saved_models/weights.best.InceptionV3.hdf5
6680/6680 [==============================] - 3s - loss: 1.1416 - acc: 0.7127 - val_loss: 0.6171 - val_acc: 0.8084
Epoch 2/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.4599 - acc: 0.8581Epoch 00001: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.4603 - acc: 0.8579 - val_loss: 0.7097 - val_acc: 0.8192
Epoch 3/20
6560/6680 [============================>.] - ETA: 0s - loss: 0.3664 - acc: 0.8892Epoch 00002: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.3669 - acc: 0.8894 - val_loss: 0.6496 - val_acc: 0.8323
Epoch 4/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.2961 - acc: 0.9098Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.2952 - acc: 0.9097 - val_loss: 0.6571 - val_acc: 0.8371
Epoch 5/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.2443 - acc: 0.9241Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.2432 - acc: 0.9241 - val_loss: 0.6834 - val_acc: 0.8467
Epoch 6/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1999 - acc: 0.9367Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.2001 - acc: 0.9368 - val_loss: 0.7318 - val_acc: 0.8491
Epoch 7/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.1725 - acc: 0.9464Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1727 - acc: 0.9460 - val_loss: 0.7333 - val_acc: 0.8539
Epoch 8/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.1501 - acc: 0.9530Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1491 - acc: 0.9533 - val_loss: 0.7271 - val_acc: 0.8575
Epoch 9/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1230 - acc: 0.9619Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1236 - acc: 0.9617 - val_loss: 0.8434 - val_acc: 0.8383
Epoch 10/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.1108 - acc: 0.9655Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.1105 - acc: 0.9656 - val_loss: 0.7787 - val_acc: 0.8683
Epoch 11/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0895 - acc: 0.9728    Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 3s - loss: 0.0894 - acc: 0.9728 - val_loss: 0.8568 - val_acc: 0.8479
Epoch 12/20
6540/6680 [============================>.] - ETA: 0s - loss: 0.0771 - acc: 0.9774Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0772 - acc: 0.9775 - val_loss: 0.8681 - val_acc: 0.8359
Epoch 13/20
6500/6680 [============================>.] - ETA: 0s - loss: 0.0719 - acc: 0.9771Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0704 - acc: 0.9775 - val_loss: 0.8127 - val_acc: 0.8611
Epoch 14/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0617 - acc: 0.9814Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0616 - acc: 0.9814 - val_loss: 0.8468 - val_acc: 0.8611
Epoch 15/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0561 - acc: 0.9821Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0561 - acc: 0.9820 - val_loss: 0.8131 - val_acc: 0.8611
Epoch 16/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0470 - acc: 0.9850Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0480 - acc: 0.9847 - val_loss: 0.9155 - val_acc: 0.8443
Epoch 17/20
6520/6680 [============================>.] - ETA: 0s - loss: 0.0438 - acc: 0.9865Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0458 - acc: 0.9861 - val_loss: 0.9481 - val_acc: 0.8455
Epoch 18/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0407 - acc: 0.9871Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0407 - acc: 0.9871 - val_loss: 0.9137 - val_acc: 0.8527
Epoch 19/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.0377 - acc: 0.9888Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0379 - acc: 0.9886 - val_loss: 0.9708 - val_acc: 0.8515
Epoch 20/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0320 - acc: 0.9916    Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s - loss: 0.0320 - acc: 0.9916 - val_loss: 0.8891 - val_acc: 0.8515
Out[213]:
<keras.callbacks.History at 0x1689b09e8>
In [214]:
InceptionV3_model.load_weights('saved_models/weights.best.InceptionV3.hdf5')
In [219]:
# get index of predicted dog breed for each image in test set
InceptionV3_predictions = [np.argmax(InceptionV3_model.predict(np.expand_dims(feature, axis=0))) for feature in test_InceptionV3]

# report test accuracy
test_accuracy = 100*np.sum(np.array(InceptionV3_predictions)==np.argmax(test_targets, axis=1))/len(InceptionV3_predictions)
print('Test accuracy for InceptionV3: %.4f%%' % test_accuracy)
Test accuracy for InceptionV3: 78.5885%

Xception

In [220]:
### TODO: Obtain bottleneck features from pre-trained CNN InceptionV3

bottleneck_features = np.load('bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features['train']
valid_Xception = bottleneck_features['valid']
test_Xception = bottleneck_features['test']
In [221]:
Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
#Xception_model.add(Dense(512))
#Xception_model.add(Activation('tanh'))
#Xception_model.add(Dropout(0.2))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_17  (None, 2048)              0         
_________________________________________________________________
dense_26 (Dense)             (None, 133)               272517    
=================================================================
Total params: 272,517.0
Trainable params: 272,517.0
Non-trainable params: 0.0
_________________________________________________________________
In [224]:
Xception_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
In [225]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6640/6680 [============================>.] - ETA: 0s - loss: 1.0570 - acc: 0.7337      Epoch 00000: val_loss improved from inf to 0.53698, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 12s - loss: 1.0537 - acc: 0.7344 - val_loss: 0.5370 - val_acc: 0.8228
Epoch 2/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.3970 - acc: 0.8720Epoch 00001: val_loss improved from 0.53698 to 0.49742, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 5s - loss: 0.3972 - acc: 0.8716 - val_loss: 0.4974 - val_acc: 0.8455
Epoch 3/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.3243 - acc: 0.8936Epoch 00002: val_loss improved from 0.49742 to 0.48970, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 5s - loss: 0.3256 - acc: 0.8936 - val_loss: 0.4897 - val_acc: 0.8431
Epoch 4/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.2776 - acc: 0.9096Epoch 00003: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.2781 - acc: 0.9094 - val_loss: 0.5142 - val_acc: 0.8515
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.2435 - acc: 0.9246Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.2435 - acc: 0.9246 - val_loss: 0.5005 - val_acc: 0.8479
Epoch 6/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.2146 - acc: 0.9327Epoch 00005: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.2158 - acc: 0.9323 - val_loss: 0.5273 - val_acc: 0.8575
Epoch 7/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.1967 - acc: 0.9403Epoch 00006: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.1989 - acc: 0.9398 - val_loss: 0.5408 - val_acc: 0.8563
Epoch 8/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.1752 - acc: 0.9451Epoch 00007: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.1769 - acc: 0.9448 - val_loss: 0.5460 - val_acc: 0.8623
Epoch 9/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1602 - acc: 0.9495Epoch 00008: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.1604 - acc: 0.9496 - val_loss: 0.5457 - val_acc: 0.8539
Epoch 10/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1479 - acc: 0.9535Epoch 00009: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.1488 - acc: 0.9533 - val_loss: 0.5754 - val_acc: 0.8539
Epoch 11/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.1370 - acc: 0.9592Epoch 00010: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.1371 - acc: 0.9590 - val_loss: 0.5903 - val_acc: 0.8659
Epoch 12/20
6580/6680 [============================>.] - ETA: 0s - loss: 0.1248 - acc: 0.9628Epoch 00011: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.1258 - acc: 0.9627 - val_loss: 0.5996 - val_acc: 0.8587
Epoch 13/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1181 - acc: 0.9651Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.1189 - acc: 0.9647 - val_loss: 0.5946 - val_acc: 0.8599
Epoch 14/20
6640/6680 [============================>.] - ETA: 0s - loss: 0.1032 - acc: 0.9688Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 4s - loss: 0.1033 - acc: 0.9689 - val_loss: 0.6268 - val_acc: 0.8587
Epoch 15/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0967 - acc: 0.9718Epoch 00014: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.0980 - acc: 0.9714 - val_loss: 0.6427 - val_acc: 0.8527
Epoch 16/20
6600/6680 [============================>.] - ETA: 0s - loss: 0.0972 - acc: 0.9715Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.0962 - acc: 0.9719 - val_loss: 0.6545 - val_acc: 0.8551
Epoch 17/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0879 - acc: 0.9740Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.0878 - acc: 0.9740 - val_loss: 0.6326 - val_acc: 0.8599
Epoch 18/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0835 - acc: 0.9763Epoch 00017: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.0832 - acc: 0.9763 - val_loss: 0.6724 - val_acc: 0.8551
Epoch 19/20
6660/6680 [============================>.] - ETA: 0s - loss: 0.0819 - acc: 0.9779Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.0818 - acc: 0.9778 - val_loss: 0.6768 - val_acc: 0.8539
Epoch 20/20
6620/6680 [============================>.] - ETA: 0s - loss: 0.0737 - acc: 0.9787Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 5s - loss: 0.0745 - acc: 0.9784 - val_loss: 0.6415 - val_acc: 0.8563
Out[225]:
<keras.callbacks.History at 0x12c8801d0>
In [226]:
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')
In [227]:
# get index of predicted dog breed for each image in test set
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(feature, axis=0))) for feature in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Test accuracy for Xception: %.4f%%' % test_accuracy)
Test accuracy for Xception: 85.0478%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [230]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

from extract_bottleneck_features import *

def Xception_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Xception_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [245]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline  

def dog_breed_prediction(img_path):
    message = None
    obj = None
    breed = None
    
    if dog_detector(img_path):
        obj = 'dog'
        message = 'Your breed is '
    elif face_detector(img_path):
        obj = 'human'
        message = 'You look like '
    
    if not obj:
        print('No dog or human detected in this image.')
        
    breed = Xception_predict_breed(img_path)
    
    print('Hello, {}!. {} {}'.format(obj, message, breed))
    # Read in image from img_path
    img = cv2.imread(img_path)
    # Convert image from BGR to RGB colours
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # Show image
    plt.imshow(cv_rgb)
    plt.show()

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

The algorithm works perfectly in classifying the dog breeds but gives a random human breed.

Some possible improvements to the algorithm

  • Use a fully-connected layer after loading the Xception bottleneck features, which may may improve performance over the GAP layer but it will also increase computational complexity.
  • Use Data Augmentation (Rotation Invariance and Translation Invariance) to provide a larger training dataset and capture better features during training
  • Adopt Approach "Case 4: Large Data Set, Different Data" that involves:

    • Retraining the Xception CNN from scratch with randomly initialized weights (slower) instead of the current approach of initialising the weights from the pre-trained Xception CNN (faster)
  • Build several models (Xception, VGG16, VGG19, InceptionV3, ResNet50) and perform prediction on an ensemble model
In [246]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

dog_test_1 = ['dogImages/test/005.Alaskan_malamute/Alaskan_malamute_00346.jpg',
              'dogImages/test/100.Lowchen/Lowchen_06696.jpg',
              'dogImages/test/061.English_cocker_spaniel/English_cocker_spaniel_04322.jpg',
              'dogImages/test/133.Yorkshire_terrier/Yorkshire_terrier_08337.jpg',
              'dogImages/test/079.Great_pyrenees/Great_pyrenees_05413.jpg',
              'dogImages/test/123.Pomeranian/Pomeranian_07873.jpg']
for img_path in dog_test_1:
    dog_breed_prediction(img_path)
Hello, dog!. Your breed is  Alaskan_malamute
Hello, dog!. Your breed is  Lowchen
Hello, dog!. Your breed is  Cocker_spaniel
Hello, dog!. Your breed is  Yorkshire_terrier
Hello, dog!. Your breed is  Great_pyrenees
Hello, dog!. Your breed is  Pomeranian
In [248]:
human_test_1 = ['lfw/Abbas_Kiarostami/Abbas_Kiarostami_0001.jpg',
                'lfw/Pat_Summerall/Pat_Summerall_0001.jpg',
                'lfw/Bill_Gates/Bill_Gates_0006.jpg',
                'lfw/Alicia_Keys/Alicia_Keys_0001.jpg',
                'lfw/Pauline_Phillips/Pauline_Phillips_0001.jpg',
                'lfw/Amy_Gale/Amy_Gale_0001.jpg']

for img_path in human_test_1:
    dog_breed_prediction(img_path)
Hello, human!. You look like  Dachshund
Hello, human!. You look like  Dachshund
Hello, human!. You look like  Cavalier_king_charles_spaniel
Hello, human!. You look like  Dachshund
Hello, human!. You look like  Dachshund
Hello, human!. You look like  Cane_corso
In [247]:
test_images = ['test_images/andrew-ng.jpg',
                'test_images/australian-shepherd.jpg',
                'test_images/beagles.jpg',
                'test_images/bulldog.jpg',
                'test_images/cavalier.jpg',
                'test_images/chris-pratt.jpg',
                'test_images/donald-trump.jpg',
                'test_images/mark-zuckerberg.jpg',
                'test_images/mother-teresa.jpg',
                'test_images/schnauzer.jpg',
                'test_images/Standard-Poodle.jpg',
                'test_images/theresa-may.jpg',
                'test_images/chihuahua-muffin.jpg',
                'test_images/Chihuahua-or-Muffin.jpg']
for img_path in test_images:
    dog_breed_prediction(img_path)
Hello, human!. You look like  Cavalier_king_charles_spaniel
Hello, dog!. Your breed is  Australian_shepherd
Hello, dog!. Your breed is  Beagle
Hello, dog!. Your breed is  French_bulldog
Hello, dog!. Your breed is  American_foxhound
Hello, human!. You look like  Dachshund
Hello, human!. You look like  Cavalier_king_charles_spaniel
Hello, human!. You look like  Dachshund
No dog or human detected in this image.
Hello, None!. None Dachshund
Hello, dog!. Your breed is  Miniature_schnauzer
Hello, dog!. Your breed is  Poodle
Hello, human!. You look like  Afghan_hound
Hello, dog!. Your breed is  Chihuahua
Hello, dog!. Your breed is  Chihuahua
In [ ]: